package com.aimei.security.filter;

import com.aimei.security.authentication.UserAuthentication;
import com.aimei.security.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xiah
 * @date 2018/5/5 16:27
 */
public class UserSecurityFilter extends AbstractAuthenticationProcessingFilter{
       public UserSecurityFilter(String defaultFilterProcessesUrl) {
              super(defaultFilterProcessesUrl);
       }

       public UserSecurityFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
              super(requiresAuthenticationRequestMatcher);
       }

       @Override
       public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
              User uu=new User();
              uu.setUserName("小李子");
              return new UserAuthentication(uu);
       }

       @Override
       protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain
               chain,
                                               Authentication authResult) throws IOException, ServletException {
              SecurityContext context = SecurityContextHolder.createEmptyContext();
              context.setAuthentication(authResult);
              SecurityContextHolder.setContext(context);
              chain.doFilter(request, response);
       }
}
